package com.example.food.controller;

import com.example.common.AjaxResult;
import com.example.food.domain.Goods;
import com.example.food.service.FoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * 商品Controller层
 */
@RestController
@RequestMapping("/food")
public class FoodController {

    @Autowired
    private FoodService foodService;

    //查询商品列表
    @ResponseBody
    @RequestMapping("/queryList")
    public AjaxResult queryList(Goods goods) throws Exception {
        return foodService.selectList(goods);
    }

    //新增商品
    @RequestMapping("/add")
    public AjaxResult add(@RequestBody Goods goods) {
        return foodService.addOther(goods);
    }

    //新增商品
    @RequestMapping("/delete")
    public AjaxResult deleteOther(@RequestParam String goodsId) {
        foodService.removeById(goodsId);
        return AjaxResult.success();
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    @Value("${web.upload-path}")
    private String uploadPath;

    @PostMapping("/uploadFile")
    public String uploadFile(MultipartFile file, HttpServletRequest request){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        // 在 uploadPath 文件夹中通过日期对上传的文件归类保存
        // 比如：/2019/06/06/cf13891e-4b95-4000-81eb-b6d70ae44930.png
        String format = sdf.format(new Date());
        File folder = new File(uploadPath + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        // 对上传的文件重命名，避免文件重名
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            // 文件保存
            file.transferTo(new File(folder, newName));
            // 返回上传文件的访问路径
            String filePath = "/"+format + newName;
            return filePath;
        } catch (IOException e) {
            return "服务器异常";
        }
    }


}
